package com.defect.service.securityService.securityServiceImpl;

import com.defect.exception.UsernameRepeatException;
import com.defect.mapper.UserMapper;
import com.defect.po.User;
import com.defect.service.securityService.LUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class LUserServiceImpl implements LUserService, UserDetailsService {
    @Resource
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 登录认证查询账号
     *
     * @param username
     * @return UserDetails
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.selectByUsername(username);
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return user;
    }

    /**
     * 查询所有用户
     * @return
     * @throws Exception
     */
    @Override
    public List<Map<String,Object>> selectUserAll(Map<String,Object> map) throws Exception {
        return userMapper.selectUserAll(map);
    }

    /**
     * 查询用户的数量
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public long cont(Map<String, Object> map) throws Exception {
        return userMapper.count(map);
    }

    /**
     * 新增用户
     * @return
     * @throws Exception
     */
    @Override
    public User insertUser(User user) throws Exception {
        if(userMapper.selectByUsername(user.getUsername()) != null){
         throw new UsernameRepeatException("该账号已注册");
        }
        userMapper.insertSelective(user);
        return user;
    }

    /**
     * 修改用户
     * @param user
     * @return
     * @throws Exception
     */
    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    @Override
    public int updataUser(User user) throws Exception {
        return userMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 批量删除用户
     * @param arr
     * @return
     * @throws Exception
     */
    @Override
    public void delateUsers(Integer[] arr) throws Exception {
        for (int i = 0; i <arr.length ; i++) {
            userMapper.deleteByPrimaryKey(arr[i]);
        }
    }

    @Override
    public void delateUser(Integer id) throws Exception {
        userMapper.deleteByPrimaryKey(id);
    }
}
